package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.engine.IScript;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.workflow.model.ConditionScript;
import com.ccp.dev.workflow.service.ConditionScriptService;
import net.sf.json.JSONArray;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * ClassDescribe:系统条件脚本 控制器类
 * @author :jiayueqiao
 * Date: 2019-07-09
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT +UrlConstants.PROJECT_MODULE_WORKFLOW+"/conditionScript")
@Action(ownermodel = SysAuditModelType.PROCESS_AUXILIARY)
public class ConditionScriptController extends SysBaseController {
    private static final Logger logger = LoggerFactory.getLogger(ConditionScriptService.class);

    @Resource
    private ConditionScriptService conditionScriptService;

    /**
     * 跳转系统条件脚本页面
     *
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "系统条件脚本页面跳转",exectype = "页面跳转日志")
    public String viewList() {
        return getAutoView();
    }

    /**
     * 添加页面-弹窗
     * 编辑页面-弹窗
     * @param request
     * @param model
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/edit")
    @Action(description = "系统条件脚本添加、编辑页面弹窗跳转",exectype = "页面跳转日志")
    public String windowEditList(HttpServletRequest request, Model model) throws Exception {
        String id =  RequestUtil.getString(request,"id");
        //获取IScript的实现类
        List<Class> implClasses = AppUtil.getImplClass(IScript.class);
        if(StringUtil.isNotEmpty(id)) {
            String returnUrl = RequestUtil.getPrePage(request);
            ConditionScript conditionScript = conditionScriptService.getOneById(id);
            model.addAttribute("conditionScript", conditionScript)
                    .addAttribute("returnUrl", returnUrl);
        }
        model.addAttribute("implClasses", implClasses);
        return getAutoView();
    }

    /**
     * 导入页面-弹窗
     *
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/importXml")
    @Action(description = "系统条件脚本导入页面弹窗跳转",exectype = "页面跳转日志")
    public String windowImportXmlList() {
        return getAutoView();
    }

    /**
     * 获取系统条件脚本列表数据
     *
     * @param request
     * @param response
     * @return 返回数据
     */
    @RequestMapping("/selector")
    @Action(description = "系统条件脚本列表数据查询",detail = "<#if success>系统条件脚本列表数据查询成功</#if>")
    @ResponseBody
    public ResultData selector(HttpServletRequest request, HttpServletResponse response) {
        try {
            QueryFilter queryFilter = new QueryFilter(request, true);
            List<ConditionScript> list = conditionScriptService.queryList(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("operation.success",queryFilter.getPageBean().getTotalCount(), list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return getResultDataError("operation.failure",1,e.getMessage());
        }

    }

    /**
     * 删除系统条件脚本
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @Action(description = "系统条件脚本删除",execOrder = ActionExecOrder.BEFORE,
            detail = "<#if success>系统条件脚本删除成功</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        try{
            String[] ids = RequestUtil.getStringAryByStr(request,"ids");
            conditionScriptService.delByIdArray(ids);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("delete.success");
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("delete.failure",1,e.getMessage());
        }
    }

    /**
     * 保存系统条件脚本
     * @param conditionScript
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description = "系统条件脚本保存",detail = "系统条件脚本<#if add>添加成功<#else>更新成功</#if>")
    @ResponseBody
    public ResultData save(ConditionScript conditionScript){
        conditionScript.setArgument(StringEscapeUtils.unescapeHtml4(conditionScript.getArgument()));
        try{
            if(StringUtil.isNotEmpty(conditionScript.getId())){
                conditionScriptService.update(conditionScript);
                SysAuditThreadLocalHolder.putParamerter("add",false);

            }else{
                conditionScript.setId(UUIDUtils.getUUIDFor32());
                conditionScriptService.add(conditionScript);
                SysAuditThreadLocalHolder.putParamerter("add",true);
            }
            return getResultDataSuccess("save.success");
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("save.failure",1,e.getMessage());
        }
    }

    /**
     * 导入系统条件脚本
     * @param request
     * @return 返回结果
     */
    @RequestMapping("/importXml")
    @Action(description = "系统条件脚本导入",detail = "<#if success>系统条件脚本导入成功</#if>")
    @ResponseBody
    public ResultData importXml(MultipartHttpServletRequest request){
        MultipartFile fileLoad = request.getFile("file");
        try{
            conditionScriptService.importXml(fileLoad.getInputStream());
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("file.importXml.success");
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("file.importXml.failure",1,e.getMessage());
        }
    }

    /**
     * 导出系统条件脚本
     */
    @RequestMapping("/exportXml")
    @Action(description = "系统条件脚本导出",detail = "系统条件脚本导出<#if success>成功<#else>失败</#if>")
    public void exportXml(HttpServletRequest request,HttpServletResponse response){
        String strXml = null;
        String fileName = null;
        String[] tableIds = RequestUtil.getStringAryByStr(request,"tableIds");
        List<ConditionScript> list = conditionScriptService.queryList(null);
        try{
            if(BeanUtils.isEmpty(tableIds)){
                strXml = conditionScriptService.exportXml(list);
                fileName = "全部条件脚本_"+ DateFormatUtil.getNowByString("yyyyMMddHHmmdd")+ ".xml";
            }else{
                strXml = conditionScriptService.exportXml(tableIds);
                fileName = DateFormatUtil.getNowByString("yyyyMMddHHmmdd")+ ".xml";
                if(tableIds.length == 1){
                    ConditionScript conditionScript = conditionScriptService.getOneById(tableIds[0]);
                    fileName = conditionScript.getMethodName()+"_"+fileName;
                }else if(tableIds.length == list.size()){
                    fileName = "全部条件脚本_" + fileName;
                } else {
                    fileName = "多条条件脚本_" + fileName;
                }
            }
            FileUtil.downLoad(request,response,strXml,fileName);
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
    }

    /**
     * 获取所有有效的条件脚本
     * @return 返回数据
     */
    @RequestMapping("/getConditionScript")
    @Action(description = "查询所有有效的条件脚本",detail = "<#if success>所有有效的条件脚本查询成功</#if>")
    @ResponseBody
    public ResultData getConditionScript(){
        try {
            List<ConditionScript> list = conditionScriptService.queryConditionScript();
            JSONArray jarray = JSONArray.fromObject(list);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",jarray);
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("query.failure");
        }
    }

    /**
     * 获取对应类名的所有方法
     * @param request
     * @return 返回数据
     */
    @RequestMapping("/getMethodsByName")
    @Action(description = "获取对应类名的所有方法",detail = "<#if success><#assign ent=RequestUtil.getString(request,\"name\") />${ent}对应类名的所有方法查询成功</#if>")
    @ResponseBody
    public ResultData getMethodsByName(HttpServletRequest request){
        String name = RequestUtil.getString(request,"name");
        try{
            JSONArray jsonArray = conditionScriptService.getMethodsByName(name);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",jsonArray);
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("query.failure");
        }
    }

    /**
     * 验证脚本是否有效
     * @return 返回结果
     */
    @RequestMapping("/validScriptIsEnable")
    @Action(description = "验证脚本是否有效",detail = "验证脚本是否有效")
    @ResponseBody
    public ResultData validScriptIsEnable(){
        try{
            String mes = conditionScriptService.validScriptIsEnable();
            return getResultDataSuccess(mes);
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("operation.failure");
        }
    }

}